import { ElMessage } from "element-plus";
import {uuid} from "@/utils";

const baseUrl = "";
// 指定后端返回的基本数据类型
const fetch = async (url: string, options?: any): Promise<any> => {
  await nextTick();
  const reqUrl = baseUrl + url;
  return new Promise((resolve, reject) => {
    useFetch(reqUrl, {lazy:true, key:uuid(),...options })
      .then(({ data, error }: any) => {
        if (error.value) {
          ElMessage({
            message: "服务器内部错误",
            type: "error",
          });
          reject(error.value);
          return;
        }
        const value = data.value;
        if (!value) {
          console.log("执行错误了");
          // 这里处理错误回调
          resolve(value)
          // $router.replace('/reject/' + value.status)
        } else if (value.code !== 200) {
          // navigateTo('/404',{replace:true})
          // return
          ElMessage({
            message: value.msg,
            type: "error",
          });
          resolve(value)
        } else {
          resolve(value);
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};

export default new (class Http {
  get(url: string, params?: any): Promise<any> {
    return fetch(url, { method: "get", params });
  }
  postParams(url: string, params?: any): Promise<any> {
    return fetch(url, { method: "post", params });
  }
  post(url: string, body?: any): Promise<any> {
    return fetch(url, { method: "post", body });
  }

  postFile(url: string, body?: any): Promise<any> {
    return fetch(url, { method: "post", body });
  }

  put(url: string, body?: any): Promise<any> {
    return fetch(url, { method: "put", body });
  }

  delete(url: string, body?: any): Promise<any> {
    return fetch(url, { method: "delete", body });
  }
})();

